package com.bootssm.controller;

import com.bootssm.enity.PageView;
import com.bootssm.enity.Result;
import com.bootssm.enity.Student;
import com.bootssm.enity.StudentQueryVO;

import com.bootssm.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    StudentService studentService;

    @PostMapping("/findAll")
    public PageView<Student> findAll(@RequestBody StudentQueryVO studentQueryVO) {
        Integer page = studentQueryVO.getPage();
        Integer start = (page - 1) * studentQueryVO.getSize();
        studentQueryVO.setStart(start);
        List<Student> students = studentService.findAll(studentQueryVO);

        Integer count = studentService.getCount(studentQueryVO);
        PageView<Student> pageView = new PageView<>();
        pageView.setDataList(students);
        pageView.setCount(count);
        return pageView;
    }

    @GetMapping("/delete/{id}")
    public Result deleteById(@PathVariable("id") String id) {
        try {
            studentService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", "delete wrong!");
        }
        return new Result("200", "delete!");
    }

    @GetMapping("/findById/{id}")
    public Student findById(@PathVariable("id") String id) {
        Student student = studentService.findById(id);
        return student;
    }

    @PostMapping("/update")
    public Result update(@RequestBody Student student) {
        try {
            studentService.update(student);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", "update wrong!");
        }
        return new Result("200", "update!");
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody Student student) {
        try {
            studentService.insert(student);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", "save wrong!");
        }
        return new Result("200", "save!");
    }
}
